#!/bin/bash

IDF_TARGET="esp32s2"
time1=$(date "+_%m%d_%H%M")

function usage()   #show how to use this shell
{
    printf "usage: bash FILE.SH \033[32m[-h|--help] [-b|--build] [-f|--flash] [-m|--monitor]\033[0m \n"
    printf "                    \033[32m[-s|--set-target] [-c|--clean] [-g|--get-bin]\033[0m \n\n"
    printf "optional arguments:\n"
    printf "\033[32m  -h, --help              Search for help information\033[0m\n"
    printf "\033[32m  -b, --build             idf.py build\033[0m\n"
    printf "\033[32m  -f, --flash             idf.py -p /dev/ttyUSB0 flash\033[0m\n"
    printf "\033[32m  -m, --monitor           idf.py monitor\033[0m\n"
    printf "\033[32m  -s, --set-target        idf.py set-traget ${IDF_TARGET}\033[0m\n"
    printf "\033[32m  -c, --clean             idf.py clean\033[0m\n\n"
    printf "\033[32m  -g, --get-bin           backup bin file to bin${time1}\033[0m\n\n"

    exit 0
}

if [[ $# < 1 ]];then
    printf "Try 'bash [FILE.SH] --help' for more information.\n"
    exit
fi

while [ $# -gt 0 ]
do
    case $1 in
	-h|--help)
            usage
	;;
	-b|--build)
		idf.py build
	;;
	-f|--flash)
		idf.py -p /dev/ttyUSB0 flash
		if [ $? -eq 0 ];then
			idf.py -p /dev/ttyUSB0 monitor
		else
			printf "\033[32m flash is error! \033[0m\n\n"
			exit 1
		fi
	;;
	-m|--monitor)
		idf.py monitor
	;;
	-s|--set-target)
		idf.py set-target ${IDF_TARGET}
		if [ $? -ne 0 ];then
			printf "\033[32m set-target is error! \033[0m\n\n"
		fi
	;;
	-c|--clean)
		idf.py clean
		if [ $? -ne 0 ];then
			idf.py fullclean
		fi
	;;
	-g|--get-bin)
		mkdir ./bin${time1}
		for i in `find build/ -name *.bin | grep -vE "CMake|initial"`;do
			cp -a ${i} ./bin${time1}/;
		done
	;;
	*)
	    printf "Error: Unknow Options -> $*"
            printf "Try 'bash [FILE.SH] --help' for more information.\n"
	    exit 1
	;;
    esac
    shift
done

#idf.py -p /dev/ttyUSB0 flash #flash
#if [ $? -eq 0 ];then #if is ok
#	idf.py -p /dev/ttyUSB0 monitor
#else
#	idf.py set-target esp32s2
#	if [ $? -ne 0 ];then #if is error
#		idf.py clean
#		if [ $? -ne 0 ];then
#			idf.py fullclean
#		fi
#
#		idf.py set-target esp32s2
#		if [ $? -ne 0 ];then
#			printf "\033[32m set-target is error! \033[0m\n\n"
#		fi
#	fi
#	
#	idf.py -p /dev/ttyUSB0 flash
#	if [ $? -eq 0 ];then
#		idf.py -p /dev/ttyUSB0 monitor
#	else
#		printf "\033[32m flash is error! \033[0m\n\n"
#		exit 1
#	fi
#fi

